package top.yxqz.springmvc.restful.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.yxqz.springmvc.restful.dao.EmployeeDao;
import top.yxqz.springmvc.restful.pojo.Employee;
import top.yxqz.springmvc.restful.service.EmployeeService;

import java.util.Collection;

/**
 * @author: 余小小
 * @date: 2023/4/27
 * @description：
 */
@Controller
@RequestMapping("/restful")
public class EmployeeController {
    @Autowired
    private EmployeeService service;

    /**
     * 实现查询并跳转到员工界面
     * uri: /restful/employee/
     */
    @GetMapping("/employee/")
    public String goEmployee(Model model) {
        Collection<Employee> employees = service.getAll();
        model.addAttribute("employees", employees);
        return "employee";
    }

    /**
     * 跳转到添加员工界面
     * uri: /restful/employee/add
     */
    @GetMapping("/employee/add")
    public String goAddEmployee() {
        return "addemployee";
    }

    /**
     * 实现添加员工信息
     * 1，获取表单数据（实体），前端的name属性，必须和实体的字段保持一致
     * 2.调用实现的服务
     *
     * @return
     */
    @PostMapping("/employee/add")
    public String addEmployee(Employee employee) {
        service.save(employee);
//        刷新页面
        return "redirect:/restful/employee/";
    }

    /**
     * 可以拿到当前employee对象的的id值
     *
     * @return
     */
    @GetMapping("/employee/{employeeId}")
    public String goUpdateEmployee(@PathVariable("employeeId") Integer employeeId, Model model) {
        //通过id得到员工信息（要进行修改的员工对象信息）
        Employee employee = service.get(employeeId);
//        将员工信息丢入到域对象中
        model.addAttribute("getEmployee", employee);
        return "updateemployee";
    }

    /**
     * 执行修改操作
     * uri: /restful/employee/update
     *
     * @param employee
     * @return
     */
    @PutMapping("/employee/update")
    public String updateEmployee(Employee employee) {
        service.save(employee);
        return "redirect:/restful/employee/";
    }


    /**
     * 通过员工id删除员工
     *
     * @param employeeId
     * @param model
     * @return
     */

    @DeleteMapping("/employee/{employeeId}")
    public String delEmployee(@PathVariable("employeeId") Integer employeeId, Model model) {
        service.delete(employeeId);
//        将员工信息丢入到域对象中
        model.addAttribute("msg", "删除成功");
        return "redirect:/restful/employee/";
    }


}
